/** Author: JTrapp@Google.com
* 10.10.2007
*/
/** Some static configuration.*/
var rootURL="http://laterrevueduciel.googlecode.com/svn/trunk/";  // Where does the app live
var numImages=427; //Number of images/kml files
var currentZoomLevel=100;
var currentMaxZoomLevel=13;
/** Some global vars.*/
var kmlPlacemark;  // store the last read kml placemark, because it is used in map
var map = ""; // placeholder for the map. Will be initiated on first map open.
var currentImageId=1;  // placemark id of image loaded

/** Called when the gadged is loaded*/
function init() {
    initMap();
    show();
    window.setInterval("showAndZoom()", prefs.getString("interval"));
}


function showAndZoom(){
    currentZoomLevel+=2;
    if (currentZoomLevel<=currentMaxZoomLevel){
        map.setZoom(currentZoomLevel); // use a fixed zoom level...
        _gel("status").innerHTML = "Picture "+ currentImageId+ " Zoom Level "+currentZoomLevel+"/"+currentMaxZoomLevel;   
    } else {
     show();
     currentZoomLevel=6;
    }
}

function showMap(placemarkId){
    map.clearOverlays();                
    _gel("status").innerHTML =prefs.getMsg("loadingMap");
    _gel("header").innerHTML =getChildNodeValue(kmlPlacemark, "name");  
    var lat = getNodeValue(kmlPlacemark, "latitude");
    var lng = getNodeValue(kmlPlacemark, "longitude");
    var point = new GLatLng(lat, lng);
    var imageLink = getElement(kmlPlacemark, "imageLink");
    currentMaxZoomLevel = getElement(kmlPlacemark, "maxZoomLevel").firstChild.nodeValue;
    var width = imageLink.getAttribute("width");
    var contentWidth = 96;
    var height = imageLink.getAttribute("height") * contentWidth / width;
    
    var description = getChildNodeValue(kmlPlacemark, "description");
    var info = "<img src=\""
            +_IG_GetImageUrl(imageLink.firstChild.nodeValue)
            +"\" width=\"100%\">"+description;
            
    var marker = createMarker(point, info, imageLink.firstChild.nodeValue, contentWidth, height);

     map.setCenter(point, currentZoomLevel); // use a fixed zoom level...
    _gel("status").innerHTML = "Image "+placemarkId+ "("+currentImageId+") Zoom Level "+currentZoomLevel+"/"+currentMaxZoomLevel;    
 
}


/** Create the url for the kml snipplets.*/
function getURL(placemarkId){
    var lang=prefs.getMsg("lang");
    if(lang==""){
        lang="en"; // Default language
    }
    return rootURL+"pub/generdata/yab_"+lang+placemarkId+".kml"
}

/** Show the image and description as provided in the kml.*/
function show() {
   currentZoomLevel=5;
   _gel("status").innerHTML ="<a href=\""+getURL("")+"\"/>"+prefs.getMsg("loadingImage")+"</a>";
   if (prefs.getBool("random")){
       placemarkId = 1+Math.floor(Math.random()*numImages);
   } 
   else {
       currentImageId++;
       placemarkId=1+(currentImageId%numImages);    
   }
       

   if((!prefs.getBool("infinte"))&&(currentImageId>numImages)) {
    window.clearInterval();
   }

    _IG_FetchXmlContent(getURL(placemarkId), function (response) {
    if (response == null || typeof(response) != "object" ||
    response.firstChild == null){
        _gel("header").innerHTML = "<a href=\"javascript:show("+")\"/>"+prefs.getMsg("errorRetry")+"</a>";
    } else {

        var document = response.getElementsByTagName("Document");
        var kmlDoc=document[0];
        _IG_SetTitle(prefs.getMsg("title"));
         var placemarks = kmlDoc.getElementsByTagName("Placemark");

            kmlPlacemark = placemarks[0];
            showMap(placemarkId);
            }
    }, { refreshInterval: 0 }); 
           _IG_AdjustIFrameHeight();
}
/**
 * Retrieve the first child element found for a given tag starting from an element.
 * Since behaviour is different for ie and firefox, use only when the tagname is 
 * unique. Use getChildNodeValue instead to make sure, you get the direct child.s
 * This method will only look for direct childs. No grandchilds will be found.
 * For some an unknown reason, I didn't get the standard getElementsByTagNameNS 
 * to work. If you know how, please substitute and let me know.
 * This function should not be use for prefixed nodes. Use getNodeNS instead.
 *
 * @param {Element} element Some Dom element
 * @param {String} tagname The child elements tag name.
 * @return {Node}Child element or the String "[<"+tagname+"> null]" or "[<"+tagname+"> not found]". 
 */
  
  function getNodeValue(element, tagname) {
    var nodeList = element.getElementsByTagName(tagname);
    if (nodeList.length>0) {
        if (nodeList.item(0).firstChild!=null) {
                return nodeList.item(0).firstChild.nodeValue;
        } else {
                return "[<"+tagname+"> null]";
        }
    }
    return "[<"+tagname+"> not found]";
}
/**
 * Retrieve the first child element for a given tag.
 * this method will only look for direct childs. No grandchilds will be found.
 * For some an unknown reason, I didn't get the standard getElementsByTagNameNS 
 * to work. If you know how, please substitute and let me know.
  
 * @param {Element} element Some Dom element
 * @param {String} tagname The child elements tag name, which may include the namespace prefix.
 * @return {Node}Child element or the String "[<"+tagname+"> null]" or "[<"+tagname+"> not found]". 
 */
 function getChildNodeValue(element, tagname) {
     var nodeList = element.childNodes;
    for (var i = 0, node; node = nodeList[i]; i++) {
        if (node.nodeName == tagname){
           if (node.firstChild!=null){
                   return node.firstChild.nodeValue;
            }
            else {
                    //alert("Empty node: "+node.nodeName);
                    return "";
            }
        }
     }
    return null;
}
/**
 * Retrieve the first child element for a given tag.
 * this method will only look for direct childs. No grandchilds will be found.
 * For some an unknown reason, I didn't get the standard getElementsByTagNameNS 
 * to work. If you know how, please substitute and let me know.
  
 * @param {Element} element Some Dom element
 * @param {String} tagname The child elements tag name, which may include the namespace prefix.
 * @return {Node}Child element or the String "[<"+tagname+"> null]" or "[<"+tagname+"> not found]". 
 */
 function getElement(element, tagname) {
     var nodeList = element.getElementsByTagName(tagname);
     return nodeList.item(0);    
    return null;
}



/** 
* Init the map vars. This is called the first time the 
* map tab is opened.
*/
function initMap() {
    map = new GMap2(_gel("map"));
    map.setCenter(new GLatLng(0,0), 4); 
    map.setMapType(G_HYBRID_MAP);
        _gel("status").innerHTML = "Init";   
               _IG_AdjustIFrameHeight();
}


/**
 * Get a marker from the marker cache or create it for the current id and
 * the given point. 
 * @param {GLatLng} point Point in lat and long
 * @return {GMarker} gmarker
 */
function createMarker(point, info, imageLink, width, height) {

    var myIcon = new GIcon();
    myIcon.iconSize = new GSize(width+4, height+4);
    myIcon.iconAnchor = new GPoint(width+2, height+2);
    myIcon.shadowSize = new GSize(width, height);
    myIcon.infoWindowAnchor = myIcon.iconAnchor;
    myIcon.shadow = _IG_GetImageUrl(imageLink);
    myIcon.image = _IG_GetImageUrl(rootURL+"images/shadow100.png");
    
        var marker = new GMarker(point, {icon:myIcon});
                GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(info, {maxWidth : 200});
           // _gel("imageDiv").innerHTML = "<img src=\""+_IG_GetImageUrl(getNodeValue(kmlPlacemark, "imageLink"))+"\" width=\"100%\">";            
        });
        map.addOverlay(marker);

    return marker;
}
